package com.innerchic.mapper.tool;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Author:贾恒飞
 * Timer:2020/12/18 14:38
 * Model:l6
 * PackageName:com.innerchic.lib.utils
 * Node:md5加密
 */
public class MD5 {

    /**
     * md5加密
     *
     * @param str 加密字符
     * @return 32位
     */
    public static String encrypt(String str) {
        return encrypt(str, "");
    }

    /**
     * md5加密
     *
     * @param str 源
     * @param key 盐值
     * @return String, 为null时失败
     */
    public static String encrypt(String str, String key) {
        try {
            str = str + key;
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            mdInst.update(str.getBytes());
            byte[] md = mdInst.digest();
            StringBuilder hexString = new StringBuilder();
            for (byte b : md) {
                String shaHex = Integer.toHexString(b & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * md5加密
     *
     * @param bty 源
     * @return String, 为null时失败
     */
    public String encrypt(byte[] bty) {
        try {
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            mdInst.update(bty);
            byte[] md = mdInst.digest();
            StringBuilder hexString = new StringBuilder();
            for (byte b : md) {
                String shaHex = Integer.toHexString(b & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

}
